package com.shundr;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.shundr.base.BaseFragment;
import com.shundr.cargo.CargoDetailsActivity;
import com.shundr.cargo.adapter.CargoRecommendAdapter;
import com.shundr.cargo.dao.CargoDao;
import com.shundr.cargo.model.CargoInfo;
import com.shundr.common.dao.RouteDao;
import com.shundr.common.util.PrefConstants;
import com.shundr.common.util.PrefUtils;
import com.shundr.common.util.ToastHelper;
import com.shundr.common.view.CListView;
import com.shundr.common.view.CListView.OnLoadMoreListener;
import com.shundr.frame.constant.LContext;
import com.shundr.frame.http.LHttpRequest;
import com.shundr.frame.service.PushMessageReceiver;
import com.shundr.frame.service.PushMessageReceiver.ReceiverHandler;
import com.shundr.route.RouteAddActivity;
import com.shundr.route.RoutePopupwindow;
import com.shundr.route.RoutePopupwindow.OnRouteChoiceListener;
import com.shundr.route.http.RouteRequest;
import com.shundr.route.model.TruckerRouteInfo;
import com.shundr.user.LoginActivity;
import com.shundr.user.util.UserListener;
import com.shundr.user.util.UserUtil;
/**
 * 
 * OftenRouteFragment
 * 
 * @author larry 2015-5-6 下午5:38:06 
 * @version 1.0.0
 *
 */
public class OftenRouteFragment extends BaseFragment implements OnClickListener, ReceiverHandler, UserListener {

	private static final int GET_CARGO_SUCCESSED = 500;
	
	private static final int PAGE_SIZE = LContext.PAGE_SIZE;
	private int pageNo = 0;

	private CListView mListView;
	private CargoRecommendAdapter mAdapter;

	private CargoDao mCargoDao;

	protected RelativeLayout mLayoutNoContent;
	protected TextView tvNoContent;
	private LinearLayout mLayoutRouteChoice;
	
	private LinearLayout mLayoutRouteAll;
	private TextView tvFrom;
	private TextView tvTo;
	private ImageView ivArrow;
	private ImageView ivRouteImage;
	/**
	 * popup显示位置
	 */
	private View mView;

	private List<CargoInfo> mList = new ArrayList<CargoInfo>();
	private List<TruckerRouteInfo> mRoutes = new ArrayList<TruckerRouteInfo>();

	private int mStartCode = 00;
	private int mEndCode = 00;
	private ImageView ivHope;
	
	private Button btnSound;

	private RoutePopupwindow mRoutePopupwindow;
	private RouteDao mRouteDao;
	
	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler() {

		@SuppressWarnings("unchecked")
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case GET_CARGO_SUCCESSED:
				List<CargoInfo> infos = (List<CargoInfo>) msg.obj;
				if (infos != null) {
					if (infos.size() > 0) {
						if (pageNo == 0) {
							mList.clear();
							mListView.setVisibility(View.VISIBLE);
							mLayoutNoContent.setVisibility(View.GONE);
							if (infos.size() >= PAGE_SIZE) {
								mListView.setCanLoadMore(true);
								mListView.setAutoLoadMore(true);
//								mListView.setCanRefresh(true);
							} else {
								mListView.setCanLoadMore(false);
								mListView.setAutoLoadMore(false);
//								mListView.setCanRefresh(false);
							}
						}
						mList.addAll(infos);
						mAdapter.notifyDataSetChanged();
						if (pageNo == 0) {
							mListView.setSelection(0);
						}
						pageNo = pageNo + 1;
					} else {
						if (pageNo == 0) {
							mListView.setVisibility(View.GONE);
							mLayoutNoContent.setVisibility(View.VISIBLE);
						} else {
							ToastHelper.toastLong(getActivity(), "最后一页");
						}
					}
				}
				// ProgressDialogHelper.dismiss();
				mListView.onRefreshComplete();
				mListView.onLoadMoreComplete();
				break;
			case RouteRequest.GET_ROUTE_LIST_SUCCESSED:
				mRoutes = (List<TruckerRouteInfo>)msg.obj;
				if(mRoutes!=null){
					if(mRoutes.size() == 0){
						mLayoutRouteAll.setVisibility(View.INVISIBLE);
						tvFrom.setText("所有路线");
						ivArrow.setVisibility(View.INVISIBLE);
						tvTo.setVisibility(View.INVISIBLE);
						mStartCode = 00;
						mEndCode = 00;
						ivHope.setImageResource(R.drawable.iv_no_route);
					}else{
						boolean has = false;
						for(TruckerRouteInfo info : mRoutes){
							if(info.getCargoSrcCode() == mStartCode && info.getCargoDstCode() == mEndCode){
								has = true;
							}
						}
						if(!has){
							tvFrom.setText("所有路线");
							ivArrow.setVisibility(View.INVISIBLE);
							tvTo.setVisibility(View.INVISIBLE);
							mStartCode = 00;
							mEndCode = 00;
						}
						mLayoutRouteAll.setVisibility(View.VISIBLE);
					}
				}
				break;
			case LHttpRequest.REQUEST_FAILED:
				mListView.onLoadMoreComplete();
				mListView.onRefreshComplete();
				ToastHelper.toastShort(getActivity(), msg.obj.toString());
				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
	};
	
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
	}

	@SuppressLint("InflateParams")
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_often_route, null);
		initView(view);
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {//
		super.onActivityCreated(savedInstanceState);
		PushMessageReceiver.mReceiverListeners.add(this);
		UserUtil.mUserListeners.add(this);
		mRouteDao=new RouteDao();
		refresh();
	}

	public void initView(View view) {
		mCargoDao = new CargoDao();
		mLayoutRouteAll = (LinearLayout)view.findViewById(R.id.layout_route_choice);
		mLayoutRouteChoice=(LinearLayout)view.findViewById(R.id.layout_route_oftens);
		tvFrom=(TextView)view.findViewById(R.id.tv_from);
		tvTo=(TextView)view.findViewById(R.id.tv_to);
		mView=(View)view.findViewById(R.id.view_show);
		ivArrow=(ImageView)view.findViewById(R.id.iv_arrow);
		ivRouteImage=(ImageView)view.findViewById(R.id.iv_route_choice_image);
		mLayoutRouteChoice.setOnClickListener(this);
		mListView = (CListView) view.findViewById(R.id.lv_list);
		mAdapter = new CargoRecommendAdapter(mList, getActivity());
		mListView.setAdapter(mAdapter);
		mListView.setCanLoadMore(true);
		mListView.setAutoLoadMore(true);
		mListView.setCanRefresh(false);
		mListView.setOnLoadListener(new OnLoadMoreListener() {
			@Override
			public void onLoadMore() {
				getList();
			}
		});
		mListView.setCanLoadMore(false);
		mListView.setAutoLoadMore(false);
		mListView.setCanRefresh(false);
		mLayoutNoContent = (RelativeLayout) view.findViewById(R.id.layout_no_content);
		tvNoContent = (TextView) view.findViewById(R.id.tv_no_content);
		ivHope=(ImageView)view.findViewById(R.id.iv_hope);
		ivHope.setImageResource(R.drawable.iv_no_cargo_of_this_route);
		listViewOnClick();
		tvFrom.setText("所有路线");
		ivArrow.setVisibility(View.INVISIBLE);
		tvTo.setVisibility(View.INVISIBLE);
		tvNoContent.setOnClickListener(this);
		ivHope.setOnClickListener(this);
		
		btnSound = (Button)view.findViewById(R.id.btn_sound);
		btnSound.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				boolean sound = PrefUtils.getPrefBoolean(mContext, PrefConstants.IS_TTS_ON, true);
				if(sound){
					btnSound.setText("播报已关闭");
					PrefUtils.setPrefBoolean(mContext, PrefConstants.IS_TTS_ON, false);
					LContext.isTtsOpened = false;
					btnSound.setBackgroundResource(R.drawable.circle_text_sound_close);
				}else{
					btnSound.setText("播报已开启");
					PrefUtils.setPrefBoolean(mContext, PrefConstants.IS_TTS_ON, true);
					LContext.isTtsOpened = true;
					btnSound.setBackgroundResource(R.drawable.circle_text_sound_open);
				}
				
			}
		});
	}

	/**
	 * listview点击事件
	 */
	private void listViewOnClick() {
		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
				if (LContext.isLogin()) {
					CargoInfo info = mList.get(position - 1);
					String cargoId = info.getCargoId() + "";
					Intent intent = new Intent(getActivity(),CargoDetailsActivity.class);
					intent.putExtra("CargoId", cargoId);
					startActivity(intent);
					info.setLocalType(CargoInfo.CargoLocalType.history);
					mCargoDao.updateUnRead(info);
					mAdapter.notifyDataSetChanged();
				} else {
					startActivity(new Intent(getActivity(), LoginActivity.class));
				}
			}
		});
	}
	
	public void checkSound(){
		boolean sound = PrefUtils.getPrefBoolean(mContext, PrefConstants.IS_TTS_ON, true);
		if(sound){
			btnSound.setText("播报已开启");
			btnSound.setBackgroundResource(R.drawable.circle_text_sound_open);
		}else{
			btnSound.setText("播报已关闭");
			btnSound.setBackgroundResource(R.drawable.circle_text_sound_close);
		}
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		UserUtil.mUserListeners.remove(this);
		PushMessageReceiver.mReceiverListeners.remove(this);
		releaseImageView(ivArrow);
		releaseImageView(ivHope);
		releaseImageView(ivRouteImage);
	}

	@Override
	public void onResume() {
		super.onResume();
		if(LContext.isLogin()){
//			new RouteRequest(mContext, mHandler).getRouteList();
			mHandler.postDelayed(new Runnable() {
				
				@Override
				public void run() {
					List<TruckerRouteInfo> list = mRouteDao.getRouteList(LContext.USER_ID);
					Message message = new Message();
					message.obj = list;
					message.what = RouteRequest.GET_ROUTE_LIST_SUCCESSED;
					mHandler.sendMessage(message);
				}
			}, 0);
		}
	}
	
	private void getList(){
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				List<CargoInfo> list = mCargoDao.getCargoListByRoute(mStartCode, mEndCode, pageNo*PAGE_SIZE, PAGE_SIZE);
				Message message = new Message();
				message.what = GET_CARGO_SUCCESSED;
				message.obj = list;
				mHandler.sendMessage(message);
			}
		}).start();
	}
	
	private void refresh(){
		try {
			if(LContext.isLogin()){
				pageNo = 0;
				getList();
				tvNoContent.setText("暂时没有相关路线货源");
				mListView.setVisibility(View.VISIBLE);
				mLayoutNoContent.setVisibility(View.GONE);
				mLayoutRouteAll.setVisibility(View.VISIBLE);
				btnSound.setVisibility(View.VISIBLE);
//				new RouteRequest(mContext, mHandler).getRouteList();
				ivHope.setImageResource(R.drawable.iv_no_cargo_of_this_route);
				mHandler.postDelayed(new Runnable() {
					
					@Override
					public void run() {
						List<TruckerRouteInfo> list = mRouteDao.getRouteList(LContext.USER_ID);
						Message message = new Message();
						message.obj = list;
						message.what = RouteRequest.GET_ROUTE_LIST_SUCCESSED;
						mHandler.sendMessage(message);
					}
				}, 0);
			}else{
				btnSound.setVisibility(View.GONE);
				mLayoutRouteAll.setVisibility(View.INVISIBLE);
				mListView.setVisibility(View.GONE);
				tvNoContent.setText("您还未登录，点我登录");
				mLayoutNoContent.setVisibility(View.VISIBLE);
				ivHope.setImageResource(R.drawable.iv_no_login);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void initPopup(){
		mRoutePopupwindow=new RoutePopupwindow(mContext);
		mRoutePopupwindow.setOnRouteChoiceListener(new OnRouteChoiceListener() {
			
			@Override
			public void choiceListener(int position,TruckerRouteInfo info) {
				if(position==0){
					tvFrom.setText(info.getCargoSrcPlace()+"");
					ivArrow.setVisibility(View.INVISIBLE);
					tvTo.setVisibility(View.INVISIBLE);
					mStartCode = 00;
					mEndCode = 00;
				}else{
					ivArrow.setVisibility(View.VISIBLE);
					tvTo.setVisibility(View.VISIBLE);
					tvFrom.setText(info.getCargoSrcPlace()+"");
					tvTo.setText(info.getCargoDstPlace()+"");
					mStartCode = info.getCargoSrcCode();
					mEndCode = info.getCargoDstCode();
				}
				refresh();
			}
		});
		mRoutePopupwindow.setOnDismissListener(new OnDismissListener() {
			
			@Override
			public void onDismiss() {
				ivRouteImage.setBackgroundResource(R.drawable.iv_arrow_down);
			}
		});
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tv_no_content:
			if(!LContext.isLogin()){
				startActivity(new Intent(mContext, LoginActivity.class));
			}
			break;
		case R.id.iv_hope:
			if(!LContext.isLogin()){
				startActivity(new Intent(mContext, LoginActivity.class));
			}else{
				if(mRoutes.size() == 0){
					startActivity(new Intent(mContext, RouteAddActivity.class));
				}
			}
			break;
		case R.id.layout_route_oftens:
			if(LContext.isLogin()){
				initPopup();
				mRoutePopupwindow.showPopupWindow(mView);//
				ivRouteImage.setBackgroundResource(R.drawable.iv_arrow_up);
			}else{
				startActivity(new Intent(mContext, LoginActivity.class));
			}			
			break;
		default:
			break;
		}
	}
	
	@Override
	public void onReceived(int type) {
		refresh();
	}

	@Override
	public void onUserChanged(int flag) {
		refresh();
	}
}
